<template>
  <div class="membership-page">
    <div class="container">
      <h1 class="page-title">办公工具箱会员计划</h1>
      
      <div class="membership-options">
        <div class="membership-card">
          <div class="card-header">
            <h2>免费用户</h2>
            <div class="price">
              <span class="price-value">¥0</span>
              <span class="price-period">永久</span>
            </div>
          </div>
          <div class="card-content">
            <ul class="features-list">
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>基础文本处理工具</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>基础图像处理工具</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>每日有限次数使用</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>本地处理，无上传隐私风险</span>
              </li>
              <li class="disabled">
                <el-icon class="feature-icon"><Close /></el-icon>
                <span>高级格式转换功能</span>
              </li>
              <li class="disabled">
                <el-icon class="feature-icon"><Close /></el-icon>
                <span>OCR文字识别功能</span>
              </li>
              <li class="disabled">
                <el-icon class="feature-icon"><Close /></el-icon>
                <span>批量处理功能</span>
              </li>
            </ul>
          </div>
          <div class="card-footer">
            <router-link to="/" class="btn btn-outline">开始使用</router-link>
          </div>
        </div>
        
        <div class="membership-card pro">
          <div class="card-badge">推荐</div>
          <div class="card-header">
            <h2>Pro会员</h2>
            <div class="price">
              <span class="price-value">¥5</span>
              <span class="price-period">/ 月</span>
            </div>
          </div>
          <div class="card-content">
            <ul class="features-list">
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>全部免费功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>高级格式转换功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>OCR文字识别功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>PDF高级操作</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>AI辅助生成功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>无限次使用所有功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>批量处理功能</span>
              </li>
            </ul>
          </div>
          <div class="card-footer">
            <el-button type="warning" class="upgrade-btn" @click="handleUpgrade">立即升级</el-button>
          </div>
        </div>
        
        <!-- <div class="membership-card">
          <div class="card-header">
            <h2>企业版</h2>
            <div class="price">
              <span class="price-value">¥99</span>
              <span class="price-period">/ 月</span>
            </div>
          </div>
          <div class="card-content">
            <ul class="features-list">
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>全部Pro会员功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>多用户账号(10个)</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>团队协作功能</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>高级数据安全保障</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>专属客户支持</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>定制化解决方案</span>
              </li>
              <li>
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>API集成支持</span>
              </li>
            </ul>
          </div>
          <div class="card-footer">
            <el-button type="default" class="contact-btn" @click="handleContact">联系销售</el-button>
          </div>
        </div> -->
      </div>
      
      <div class="faq-section">
        <h2 class="section-title">常见问题</h2>
        <el-collapse>
          <el-collapse-item title="如何升级到Pro会员？" name="1">
            <p>登录后，您可以点击右上角的用户头像，在下拉菜单中选择"升级会员"，然后按照提示完成付款流程即可成为Pro会员。</p>
          </el-collapse-item>
          <el-collapse-item title="会员是否自动续费？" name="2">
            <p>是的，会员采用订阅模式，将在到期时自动续费。您可以随时在个人中心取消自动续订。</p>
          </el-collapse-item>
          <el-collapse-item title="如果不想继续使用Pro会员，如何取消？" name="3">
            <p>您可以在个人中心的会员管理页面取消订阅。取消后，您将继续享有Pro会员权益直到当前订阅周期结束。</p>
          </el-collapse-item>
          <el-collapse-item title="企业版包含哪些额外功能？" name="4">
            <p>企业版包含多用户账号管理、团队协作功能、高级安全保障、专属客户支持、定制化解决方案和API集成支持等更多适合企业使用的功能。</p>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 会员计划页面
 * 展示会员特权和不同计划的对比
 */
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check, Close } from '@element-plus/icons-vue';
// 导入API服务
import { MembershipService } from '../../services';

const store = useStore();
const router = useRouter();

const loading = ref(false);
const membershipPlans = ref([]);
const membershipStatus = ref(null);
const activeTab = ref('current-plan');
const paymentDialogVisible = ref(false);
const selectedPlan = ref(null);
const paymentMethod = ref('wechat');
const isUpgrading = ref(false);
const transactionHistory = ref([]);
const loadingTransactions = ref(false);

/**
 * 获取会员计划列表
 * 无论用户是否登录都可以查看会员计划
 */
const getMembershipPlans = async () => {
  loading.value = true;
  try {
    const response = await MembershipService.getMembershipPlans();
    membershipPlans.value = response.data;
  } catch (error) {
    ElMessage.error('获取会员计划失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 获取会员状态
 * 只有用户登录后才需要获取会员状态
 */
const getMembershipStatus = async () => {
  if (!store.state.isLoggedIn) return;
  
  loading.value = true;
  try {
    const response = await MembershipService.getMembershipStatus();
    membershipStatus.value = response.data;
  } catch (error) {
    ElMessage.error('获取会员状态失败');
  } finally {
    loading.value = false;
  }
};

// 选择会员计划
const choosePlan = (plan) => {
  if (!store.state.isLoggedIn) {
    promptLogin();
    return;
  }
  
  selectedPlan.value = plan;
  paymentDialogVisible.value = true;
};

/**
 * 提示用户登录
 */
const promptLogin = () => {
  ElMessageBox.confirm('需要先登录才能升级到Pro会员', '提示', {
    confirmButtonText: '去登录',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 存储用户意图，登录后可以直接跳转到升级页面
    sessionStorage.setItem('postLoginAction', 'upgrade');
    // 跳转到登录页面
    router.push('/login');
  }).catch(() => {});
};

// 支付处理
const handlePayment = async () => {
  if (!store.state.isLoggedIn) {
    promptLogin();
    return;
  }
  
  if (!selectedPlan.value) {
    ElMessage.warning('请选择会员计划');
    return;
  }
  
  isUpgrading.value = true;
  
  try {
    // 模拟支付成功，获取订单ID
    const orderId = 'ORD' + Date.now().toString();
    
    // 调用升级会员API
    const response = await MembershipService.upgradeMembership({
      planId: selectedPlan.value.id,
      paymentMethod: paymentMethod.value,
      orderId: orderId
    });
    
    // 更新会员状态
    membershipStatus.value = response.data.membershipStatus;
    
    // 更新用户信息
    store.commit('upgradeToPro', membershipStatus.value.proExpiryDate);
    
    ElMessage.success('会员升级成功！');
    paymentDialogVisible.value = false;
    
    // 刷新交易记录
    getTransactionHistory();
  } catch (error) {
    ElMessage.error(error.message || '处理支付失败，请稍后再试');
  } finally {
    isUpgrading.value = false;
  }
};

// 取消会员
const cancelMembership = async () => {
  if (!store.state.isLoggedIn) {
    promptLogin();
    return;
  }
  
  ElMessageBox.confirm(
    '确定要取消专业版会员吗？取消后将立即失去专业版权益。',
    '取消确认',
    {
      confirmButtonText: '确定取消',
      cancelButtonText: '再考虑一下',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true;
    try {
      await MembershipService.cancelMembership();
      
      // 更新会员状态
      await getMembershipStatus();
      
      // 更新用户状态
      store.commit('upgradeToPro', null);
      
      ElMessage.success('已成功取消专业版会员');
    } catch (error) {
      ElMessage.error(error.message || '取消会员失败，请稍后再试');
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 获取交易历史
const getTransactionHistory = async () => {
  if (!store.state.isLoggedIn) return;
  
  loadingTransactions.value = true;
  try {
    const response = await MembershipService.getTransactions();
    transactionHistory.value = response.data.transactions || [];
  } catch (error) {
    console.error('获取交易记录失败', error);
  } finally {
    loadingTransactions.value = false;
  }
};

// 格式化交易状态
const formatTransactionStatus = (status) => {
  const statusMap = {
    'completed': '已完成',
    'pending': '处理中',
    'failed': '失败',
    'refunded': '已退款'
  };
  return statusMap[status] || status;
};

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const methodMap = {
    'wechat': '微信',
    'alipay': '支付宝',
    'card': '银行卡',
    'paypal': 'PayPal'
  };
  return methodMap[method] || method;
};

// 组件挂载时获取会员信息
onMounted(async () => {
  // 获取会员计划信息，无论是否登录都可以查看
  await getMembershipPlans();
  
  // 只有登录状态才需要获取会员状态和交易历史
  if (store.state.isLoggedIn) {
    await Promise.all([
      getMembershipStatus(),
      getTransactionHistory()
    ]);
  }
});

// 处理升级按钮点击
const handleUpgrade = () => {
  if (!store.state.isLoggedIn) {
    promptLogin();
    return;
  }
  
  // 已登录则显示升级对话框
  document.querySelector('.user-avatar')?.click();
  setTimeout(() => {
    document.querySelector('[data-command="upgradeToPro"]')?.click();
  }, 100);
};

// 处理联系销售按钮点击
const handleContact = () => {
  ElMessageBox.alert('请发送邮件至 business@officetoolbox.com 联系我们的销售团队，我们将尽快回复您。', '联系我们', {
    confirmButtonText: '知道了',
    type: 'success'
  });
};
</script>

<style scoped>
.membership-page {
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  text-align: center;
  margin-bottom: 40px;
  color: var(--black);
  font-size: 2rem;
  font-weight: 600;
}

.membership-options {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  justify-content: center;
  margin-bottom: 60px;
}

.membership-card {
  flex: 1;
  min-width: 300px;
  max-width: 350px;
  background-color: var(--white);
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
}

.membership-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.12);
}

.membership-card.pro {
  border: 2px solid var(--pro-color);
  transform: scale(1.05);
  z-index: 1;
}

.membership-card.pro:hover {
  transform: scale(1.05) translateY(-10px);
}

.card-badge {
  position: absolute;
  top: 15px;
  right: 15px;
  background: linear-gradient(135deg, var(--pro-color) 0%, var(--pro-light) 100%);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 600;
  box-shadow: 0 3px 6px rgba(var(--pro-color-rgb), 0.3);
}

.card-header {
  padding: 25px 20px;
  text-align: center;
  background: var(--light-gray);
  border-bottom: 1px solid var(--medium-gray);
}

.pro .card-header {
  background: linear-gradient(135deg, rgba(var(--pro-color-rgb), 0.1) 0%, rgba(var(--pro-color-rgb), 0.05) 100%);
  border-bottom: 1px solid rgba(var(--pro-color-rgb), 0.2);
}

.card-header h2 {
  margin: 0 0 15px 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--black);
}

.pro .card-header h2 {
  color: var(--pro-dark);
}

.price {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 5px;
}

.price-value {
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--black);
}

.pro .price-value {
  color: var(--pro-dark);
}

.price-period {
  font-size: 1rem;
  color: var(--dark-gray);
}

.card-content {
  padding: 25px 20px;
  flex-grow: 1;
}

.features-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.features-list li {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: var(--black);
  font-size: 1rem;
  transition: transform 0.2s ease;
}

.features-list li:hover {
  transform: translateX(5px);
}

.features-list li.disabled {
  color: var(--medium-gray);
}

.feature-icon {
  margin-right: 10px;
  border-radius: 50%;
  background-color: rgba(var(--primary-color-rgb), 0.1);
  padding: 5px;
  color: var(--primary-color);
}

.pro .feature-icon {
  background-color: rgba(var(--pro-color-rgb), 0.1);
  color: var(--pro-color);
}

.disabled .feature-icon {
  background-color: var(--light-gray);
  color: var(--medium-gray);
}

.card-footer {
  padding: 20px;
  text-align: center;
  border-top: 1px solid var(--medium-gray);
}

.pro .card-footer {
  border-top: 1px solid rgba(var(--pro-color-rgb), 0.2);
}

.btn {
  display: inline-block;
  padding: 10px 24px;
  font-size: 1rem;
  font-weight: 500;
  text-align: center;
  text-decoration: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-outline {
  color: var(--primary-color);
  background-color: transparent;
  border: 2px solid var(--primary-color);
}

.btn-outline:hover {
  background-color: rgba(var(--primary-color-rgb), 0.05);
  transform: translateY(-3px);
}

.upgrade-btn {
  background: linear-gradient(135deg, var(--pro-color) 0%, var(--pro-light) 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(var(--pro-color-rgb), 0.3);
}

.upgrade-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(var(--pro-color-rgb), 0.4);
}

.contact-btn {
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.contact-btn:hover {
  transform: translateY(-3px);
}

.faq-section {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  text-align: center;
  margin-bottom: 30px;
  color: var(--black);
  font-size: 1.5rem;
  font-weight: 600;
}

:deep(.el-collapse) {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-collapse-item__header) {
  padding: 15px 20px;
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--primary-color);
  background-color: var(--white);
  border-bottom: 1px solid var(--medium-gray);
}

:deep(.el-collapse-item__content) {
  padding: 15px 20px;
  background-color: var(--white);
  color: var(--dark-gray);
  font-size: 1rem;
  line-height: 1.6;
}

@media (max-width: 768px) {
  .membership-options {
    flex-direction: column;
    align-items: center;
  }
  
  .membership-card {
    width: 100%;
    max-width: 100%;
  }
  
  .membership-card.pro {
    transform: none;
    order: -1;
    margin-bottom: 20px;
  }
  
  .membership-card.pro:hover {
    transform: translateY(-10px);
  }
}
</style> 